function openWindow(URL,Name,features){
  var w=window.open(URL,Name,features);
}

/* Challenge related functions */
function redirectToGame() {
  window.location = "/BattleShips/layout.html";
}


function challengePopup(id, name) {
  var accept = $("<a />").attr({class: "GameButton", id: "acceptButtonEnd"}).text("Yes");
  accept.on("click", {id: id}, function(e) {
    $.post("BattleServlet", {"action":"challengeAnswer", "answer":"accept"}, function(resp) {
      if (resp == "accept")
        redirectToGame();
      else {
        alert("Accept failed, "+resp);
        disablePopup();
      }
    });
  });
  var decline = $("<a />").attr({class: "GameButton", id: "declineButtonEnd"}).text("No");
  decline.on("click", function() {
    $.post("BattleServlet", {"action":"challengeAnswer", "answer":"decline"});
  });
  $(".popup").html("<h2>Would you like to accept challenge from "+name+"?");
  $(".popup").append(accept);
  $(".popup").append(decline);    
  $(".popup").loadPopup();
}

function startGame(e) {
  console.log(window.popup);
  if (typeof(window.popup) != 'undefined') {
    window.popup.close();
    delete window.popup;
  }
  var name = e.data.name, id = e.data.id;
  console.log(e);
  $(".popup").html("<h2>Waiting for "+name+" to accept...</h2>");
  $(".popup").append("<p id='waitingText' />");
  $.post("BattleServlet", {"action": "challenge", "id":id}, function(resp) {
    //alert(resp);
    if (resp == "accept")
      redirectToGame();
    if (resp == "decline")
      disablePopup();
  });
  var loop = function(x, opponent) {
    $("#waitingText").text("Closing in "+x+" seconds.");
    console.log("Waiting..." + x + new Date());
    if (x == 0) {
      disablePopup();
      return;
    }
    else
      setTimeout(loop, 1000, x-1, opponent);
  };
  loop(30, id);
}

//Some child sent data? Currently only for new game.
window.onmessage = function(e) {
  var t = e.data.split("&", 2);
  var id = t[0], name = t[1];
  var accept = $("<a />").attr({class: "GameButton", id: "acceptButtonEnd"}).text("Yes");
  accept.on("click", {id: id, name: name}, startGame);
  var decline = $("<a />").attr({class: "GameButton", id: "declineButtonEnd"}).text("No");
  decline.on("click", disablePopup);
  $(".popup").html("<h2>Would you like to play with "+name+"?");
  $(".popup").append(accept);
  $(".popup").append(decline);
  $(".popup").loadPopup();
};

function newGamePopup() {
  window.popup = window.open('newbattle.html','Site','width=300,height=800 scrollbars=1');
}

/* Chat related functions */
 
/* Displays chat message */
function postChat(style, message) {
  if (message == "" || message == null)
    return;
  // limit the size of chat
  if ($("#chat > p").length >= 100)
    $("#chat > p:first").remove();
  
  message = $("<p />").text(message);
  //special styles
  if (style == "randomBold") 
    message.css("color", randomColor()).appendTo("#chat");
  else if (style)
    message.addClass(style);
  //add to area and scroll to bottom
  $("#chat").append(message);
  $("#chat").scrollTop($("#chat")[0].scrollHeight); 
}

/* Updates top lists */
function updateLists() {
  $.get("Chat?updates=true", function(resp) {
    var lists = $.parseJSON(resp);
    var users = $.parseJSON(lists.users);
    users.sort(function(a, b) {
      var as = a.games != '0' ? a.wins / a.games : -1;
      var bs = b.games != '0' ? b.wins / b.games : -1;
      if (as != bs)
        return bs - as;
      return a.name < b.name ? -1 : 1;
    });
    var games = $.parseJSON(lists.games);
    console.log(lists);
    $("#activeGames").html("");
    for (var i = 0; i < games.length; i++) {
      $("<li />").text(games[i].p1_name + " vs " + games[i].p2_name)
            .appendTo($("#activeGames"));
    }
    var ln = users.length > 10 ? 10 : users.length;
    $("#topPlayers").html("");
    for (var i = 0; i < ln; i++) {
      $("<li />").text(users[i].name + " " + users[i].wins + "/" + users[i].games)
            .appendTo($("#topPlayers"));
    }
    $("#pastGames").html("");
    var games = localStorage["gamesCount"];
    if (games === null) games = 0;
    else games = parseInt(games);
    for (var i = 0; i < games; i++) {
      var game = JSON.parse(localStorage["game"+i]);
      var obj = $("<li />").text(game.myname + " vs " + game.oppname);
      obj.on("click", {game: game, id:i}, function(e) {
        console.log(e.data.game);
        // Redirecting to playback
        window.location = "layout.html?playback="+e.data.id;
      });
      obj.appendTo($("#pastGames"));
    }
  });
}

function getNewMessage() {
  $.get("Chat", function(resp) {
    console.log("Got new: " + resp);
    if (resp == "update")
      updateLists();
    else if (resp.split("&")[0] == "challenge") {
      var id = resp.split("&", 3)[1], name = resp.split("&", 3)[2];
      challengePopup(id, name);        
    }
    else
      postChat(null, resp);
    getNewMessage();
  });
}

function getAllMessages() {
  $.get("Chat?all=true", function(resp) {
    console.log(resp);
    lines = resp.split("\n");
    for (var i = 0; i < lines.length; i++)
      postChat(null, lines[i]);
    getNewMessage();
  });    
}

/* Textarea helper (for chat) */
function isNotMax(event, oTextArea) {
  if (event.keyCode == 13) { //enter was presed!
    //postChat(null, null);
    var message = $.trim($("textarea").val());
    if (message != "") {
      $.post("Chat", {"message" : message});
      $("textarea").val(""); //clear chat box
    }
    return false;
  }
  return oTextArea.value.length <= oTextArea.getAttribute('maxlength');
}

/* misc */
//has username? no? change that
function checkUsername() {
  $.post("BattleServlet", {"action": "hasUsername"}, function (resp) {
    if (resp == "1") {
      console.log("Already got your name");
      return;
    }
    var name = prompt("Enter username");
    $.post("BattleServlet", {"action": "setUsername", "name": name});
  });
}
  
//player should be playing?
function checkPlayingStatus() {
  $.post("BattleServlet", {"action":"gameStatus"}, function(resp) {
    //should be playing
    console.log("Gamestatus: "+resp);
    if (resp != "")
      redirectToGame();
  });
}